package api

import (
	"context"
	"net/http"
	"portal_api/global"
	"portal_api/models/request"
	"portal_api/models/response"

	pb "portal_api/proto"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// PostRegisterPortalDevice 新建 portal device
func PostRegisterPortalDevice(c *gin.Context) {
	// 表单验证
	var registerPortalDeviceReq request.RegisterPortalDeviceReq
	if err := c.ShouldBindJSON(&registerPortalDeviceReq); err != nil {
		HandleValidatorError(c, err)
		return
	}

	_, err := global.PortalRpcClient.CreatePortalDevice(context.Background(), &pb.CreatePortalDeviceRequest{
		MacAddress: registerPortalDeviceReq.MacAddress,
		PortalCode: registerPortalDeviceReq.PortalCode,
	})

	if err != nil {
		zap.L().Error("创建portal device失败",
			zap.Error(err),
			zap.String("portal_code",
				registerPortalDeviceReq.PortalCode),
			zap.String("mac_address", registerPortalDeviceReq.MacAddress),
		)
		c.JSON(http.StatusOK, response.Response{

			Code:    http.StatusBadRequest,
			Message: "创建portal device失败",
		})
		return
	}

	c.JSON(http.StatusOK, response.Response{
		Code:    http.StatusOK,
		Message: "success",
	})
}

func GetPortalDeviceByMacAddress(c *gin.Context) {

	// 表单验证
	var req request.GetPortalDeviceByMacAddressReq
	if err := c.ShouldBindUri(&req); err != nil {
		HandleValidatorError(c, err)
		return
	}

	resp, err := global.PortalRpcClient.GetPortalDeviceByMacAddress(context.Background(), &pb.GetPortalDeviceByMacAddressRequest{
		MacAddress: req.MacAddress,
	})
	if err != nil {

		zap.L().Error("获取设备信息失败",
			zap.Error(err),
			zap.String("mac_address",
				req.MacAddress),
		)
		c.JSON(http.StatusOK, response.Response{
			// TODO: 数据库存储失败的错误码
			Code:    http.StatusBadRequest,
			Message: "获取设备信息失败",
		})
		return
	}

	c.JSON(http.StatusOK, response.Response{
		Code:    http.StatusOK,
		Message: "success",
		Data: response.GetPortalDeviceResponse{
			ID:         int(resp.Id),
			PortalCode: resp.PortalCode,
			MacAddress: resp.MacAddress,
		},
	})
}

func GetPortalDeviceByPortalCode(c *gin.Context) {

	// 表单验证
	var req request.GetPortalDeviceByPortalCodeReq
	if err := c.ShouldBindUri(&req); err != nil {
		HandleValidatorError(c, err)
		return
	}

	resp, err := global.PortalRpcClient.GetPortalDeviceByPortalCode(context.Background(), &pb.GetPortalDeviceByPortalCodeRequest{
		PortalCode: req.PortalCode,
	})

	if err != nil {

		zap.L().Error("获取设备信息失败",
			zap.Error(err),
			zap.String("portal_code",
				req.PortalCode),
		)
		c.JSON(http.StatusOK, response.Response{
			// TODO: 数据库存储失败的错误码
			Code:    http.StatusBadRequest,
			Message: "获取设备信息失败",
		})
		return
	}

	c.JSON(http.StatusOK, response.Response{
		Code:    http.StatusOK,
		Message: "success",
		Data: response.GetPortalDeviceResponse{
			ID:         int(resp.Id),
			PortalCode: resp.PortalCode,
			MacAddress: resp.MacAddress,
		},
	})
}
